// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,
    ctor(){
        this.oldSprite = null;
        this.touchStatus = '';
        this.captureNode = null;
        this.val = 0;
    },
    properties: {

    },
    onCollisionEnter(other, self){
        if(this.touchStatus == 'move' && this.val === 0){
            self.node.opacity = 0.8*255|0;
            let sprite = self.node.getComponent(cc.Sprite)
            sprite.spriteFrame = other.node.getComponent(cc.Sprite).spriteFrame;

            other.node.capture = true;
            other.node.targetPos = self.node.pos;
            
            this.captureNode = other.node;
        }
    },
    onCollisionExit: function (other, self) {
        if(this.touchStatus == 'move' && this.val === 0){
            self.node.opacity = 255;
            let sprite = self.node.getComponent(cc.Sprite)
            sprite.spriteFrame = this.oldSprite;

            other.node.capture = false;
            other.node.targetPos = null;
            this.captureNode = null;
        }
    },
    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        let canvas = cc.find('Canvas');
        this.oldSprite = this.node.getComponent(cc.Sprite).spriteFrame;
        this.node.on('end', ()=>{
            this.node.getComponent(cc.Sprite).spriteFrame = this.oldSprite;
        })
        canvas.on('touchStatus', (status)=>{
            this.touchStatus = status;
        })
        this.node.on('valChange', (newVal)=>{
            this.val = newVal;
            console.log('valChange', this.val)
            if(this.val !== 0){
                //console.log(this.captureNode)
                if(this.captureNode){
                    let cloneItem = cc.instantiate(this.captureNode);
                    cloneItem.setPosition(0,0);
                    this.node.addChild(cloneItem);
                    this.node.getComponent(cc.Sprite).spriteFrame = this.oldSprite;
                    this.node.opacity = 255;      
                    this.captureNode = null;              
                    //console.log(this.node);
                }
            }else{
                this.node.getComponent(cc.Sprite).spriteFrame = this.oldSprite;
                this.node.opacity = 255;
                this.node.removeAllChildren();
            }
        })
    },

    start () {

    },

    // update (dt) {},
});
